package com.dom.domweb.modular.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dom.common.constants.Constants;
import com.dom.common.exception.ServiceException;
import com.dom.common.model.vo.basic.*;
import com.dom.domweb.common.RspModel;
import com.dom.domweb.dao.entity.TStorContInfo;
import com.dom.domweb.dao.entity.TStorInfo;
import com.dom.domweb.dao.entity.TSysCodeTbl;
import com.dom.domweb.dao.service.ITStorContInfoService;
import com.dom.domweb.dao.service.ITStorInfoService;
import com.dom.domweb.dao.service.ITSysCodeTblService;
import com.xiaoleilu.hutool.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class StorInfoService extends AbstractApproveService {

    @Autowired
    private ITStorContInfoService storContInfoService;
    @Autowired
    private ITStorInfoService storInfoService;
    @Autowired
    private ITSysCodeTblService sysCodeTblService;

    public B099A findStorInfoList(B099R request) {
        Wrapper<TStorInfo> wrapper = new EntityWrapper<TStorInfo>();
        Page<TStorInfo> page = new Page<TStorInfo>();
        page.setSize(request.getPs() == 0 ? 20 : request.getPs());
        page.setCurrent(request.getPn());
        if (StringUtils.isNotEmpty(request.getAbbrName())){
            wrapper.like("abbr_name",request.getAbbrName());
        }
        if (StringUtils.isNotEmpty(request.getStorCode())){
            wrapper.and().eq("stor_code",request.getStorCode());
        }
        List<String> orderList = new ArrayList<String>();
        orderList.add("stop_date");
        orderList.add("ctime");
        wrapper.orderBy(true,orderList,false);
        Page<TStorInfo> pages = storInfoService.selectPage(page,wrapper);
        B099A result = pageToInfo(pages.getRecords());
        return result;
    }

    private B099A pageToInfo(List<TStorInfo> records) {
        B099A result = new B099A();
        List<StorInfo> list = new ArrayList<StorInfo>();
        Map<String,String> map = getStorTypeToMap();
        for (TStorInfo info: records ) {
            StorInfo Stor = storToInfo(info,map);
            list.add(Stor);
        }
        result.setStorInfoData(list);
        return result;
    }

    private Map<String,String> getStorTypeToMap(){
        List<TSysCodeTbl> list = sysCodeTblService.findSysCode(Constants.STOR_TYPE_SYS_CODE);
        Map<String,String> map = new HashMap<>();
        for (TSysCodeTbl tbl: list) {
            map.put(tbl.getSysValue(),tbl.getCodeDesc());
        }
        return map;
    }

    public String insertStorInfo(B090R request) {
        TStorInfo info = beanToInfo(request);
        boolean isTrue = storInfoService.insert(info);
        if(!isTrue){
            log.info("仓库信息新增失败, result:{}", isTrue);
            throw new ServiceException("9001", "仓库信息新增数据库异常");
        }

        List<TStorContInfo> list = new ArrayList<>();
        for (StorLinkInfo Stor:request.getStorLinkData() ) {
            TStorContInfo contInfo = beanToCont(Stor,info);
            list.add(contInfo);
        }
        isTrue = storContInfoService.insertBatch(list);
        if(!isTrue){
            log.info("仓库联系人信息新增失败, result:{}", isTrue);
            throw new ServiceException("9001", "仓库联系人信息新增数据库异常");
        }
        return info.getId().toString();
    }

    private TStorContInfo beanToCont(StorLinkInfo storLink,TStorInfo stor){
        TStorContInfo info = new TStorContInfo();
        info.setStorId(stor.getStorCode());
        info.setContId(stor.getId());
        info.setContName(storLink.getLinkName());
        info.setEmail(storLink.getLinkEmail());
        info.setSex(StringUtils.isEmpty(storLink.getLinkSex()) ? null : Integer.valueOf(storLink.getLinkSex()));
        info.setLevle(storLink.getLevel());
        info.setPhone(storLink.getLinkPhone());
        info.setMemCode(stor.getMemCode());
        info.setVersion(0);
        return info;
    }

    private StorInfo storToInfo(TStorInfo info, Map<String,String> map){
        StorInfo stor = new StorInfo();
        stor.setId(info.getId());
        stor.setAbbrName(info.getStorAbbr());
        stor.setAddress(info.getAddress());
        stor.setStorName(info.getStorName());
        stor.setMemCode(info.getMemCode());
        stor.setStorArea(info.getStorArea());
        stor.setStorPurp(info.getStorPrup());
        stor.setStat(info.getStat() == null ? null : info.getStat());
        stor.setStorType(info.getStorType() == null ? null : info.getStorType());
        stor.setStorCode(info.getStorCode());
        stor.setStorName(info.getStorName());
        stor.setStorTypeDesc(info.getStorType() == null ? null : map.get(info.getStorType().toString()));
//        stor.setStopDate(info.getStopDate() == null ? null : DateUtil.formatDate(info.getStopDate()));
        stor.setStopDate(info.getStopDate());
        stor.setCtime(info.getCtime() == null ? null : DateUtil.formatDate(info.getCtime()));
        return stor;
    }

    private TStorInfo beanToInfo(B090R request){
        TStorInfo info = new TStorInfo();
        info.setStorAbbr(request.getAbbrName());
        info.setStorId(request.getStorCode());
        info.setAddress(request.getAddress());
        info.setStorPrup(request.getStorPurp());
        info.setStorCode(request.getStorCode());
        info.setStorArea(request.getStorArea());
        info.setStorName(request.getStorName());
        info.setStorType(StringUtils.isEmpty(request.getStorType()) ? null : Integer.valueOf(request.getStorType()));
//        info.setStopDate(StringUtils.isEmpty(request.getStopDate()) ? null : DateUtil.parseDate(request.getStopDate()));
        info.setStopDate(request.getStopDate());
        info.setVersion(0);
        info.setMemCode(0);
        return info;
    }

    public B093A findUpdateStorInfoPage(String id) {
        Wrapper<TStorContInfo> wrapper = new EntityWrapper<TStorContInfo>();
        TStorInfo stor = storInfoService.selectById(id);
        B093A result = storToResult(stor);
        wrapper.eq("stor_id",stor.getStorCode());
        List<StorLinkInfo> linkList = new ArrayList<StorLinkInfo>();
        List<TStorContInfo> list = storContInfoService.selectList(wrapper);
        for (TStorContInfo cont: list) {
            StorLinkInfo info = contTolink(cont);
            linkList.add(info);
        }
        result.setStorLinkData(linkList);
        return result;
    }

    private StorLinkInfo contTolink(TStorContInfo cont){
        StorLinkInfo info = new StorLinkInfo();
        info.setLinkName(cont.getContName());
        info.setLinkPhone(cont.getPhone());
        info.setLevel(cont.getLevle());
        info.setLinkSex(cont.getSex() == null ? null : cont.getSex().toString());
        info.setLinkEmail(cont.getEmail());
        info.setId(cont.getId().toString());
        info.setStorCode(cont.getStorId() == null ? null : cont.getStorId().toString());
        return info;
    }

    private B093A storToResult(TStorInfo stor){
        B093A result = new B093A();
        result.setId(stor.getId().toString());
        result.setAbbrName(stor.getStorAbbr());
        result.setAddress(stor.getAddress());
        result.setStat(stor.getStat() == null ? null : stor.getStat().toString());
        result.setStorArea(stor.getStorArea());
        result.setStorName(stor.getStorName());
        result.setStorCode(stor.getStorCode());
        result.setStorType(stor.getStorType() == null ? null : stor.getStorType().toString());
//        result.setStopDate(stor.getStopDate() == null ? null : DateUtil.formatDate(stor.getStopDate()));
        result.setStopDate(stor.getStopDate());
        result.setStorPurp(stor.getStorPrup());
        return result;
    }

    public boolean storInfoDel(String id) {
        Wrapper<TStorContInfo> wrapper = new EntityWrapper<TStorContInfo>();

        boolean isTrue = storInfoService.deleteById(Integer.valueOf(id));
        if(!isTrue){
            log.info("仓库信息删除失败, result:{}", isTrue);
            throw new ServiceException("9001", "仓库信息删除数据库异常");
        }
        wrapper.eq("cont_id",id);
        isTrue = storContInfoService.delete(wrapper);
        if(!isTrue){
            log.info("仓库联系人信息删除失败, result:{}", isTrue);
            throw new ServiceException("9001", "仓库联系人信息删除数据库异常");
        }
        return isTrue;
    }

    public RspModel storInfoModify(B092R request) {
        Wrapper<TStorContInfo> contWrapper = new EntityWrapper<TStorContInfo>();
        TStorInfo info = modifyToStor(request);
        boolean isTrue = storInfoService.updateById(info);
        if(!isTrue){
            log.info("仓库信息修改失败, result:{}", isTrue);
            return new RspModel("RSP000003", "仓库信息修改数据库异常");
        }
        List<String> list = new ArrayList<>();
        if (request.getStorLinkData() != null && request.getStorLinkData().size() != 0){
            for (B102R link : request.getStorLinkData() ) {
                if(StringUtils.isNotEmpty(link.getKeyId())){
                    list.add(link.getKeyId());
                }
            }
        }
        contWrapper.notIn("id",list);
        contWrapper.and().eq("cont_id",request.getId());
        isTrue = storContInfoService.delete(contWrapper);
        if(!isTrue){
            log.info("仓库联系人信息修改失败, result:{}", isTrue);
            return new RspModel("RSP000002", "仓库联系人信息修改数据库异常");
        }
        List<String> contIdList = storContInfoService.selectContIdByStorId(request.getId());
        for (B102R detail : request.getStorLinkData()) {
            TStorContInfo detailFlow = toCont(detail, request);
            if (!StringUtils.isEmpty(detail.getKeyId()) &&
                    contIdList.contains(detail.getKeyId())) {
                Wrapper<TStorContInfo> detailIdWap = new EntityWrapper<TStorContInfo>();
                detailIdWap.and().eq("id", detail.getKeyId());
                storContInfoService.update(detailFlow, detailIdWap);
            } else {
                storContInfoService.insert(detailFlow);
            }
        }
        return new RspModel("RSP000000","仓库信息修改成功！");
    }

    private TStorContInfo toCont(B102R detail, B092R request) {
        TStorContInfo info = new TStorContInfo();
        info.setId(StringUtils.isEmpty(detail.getKeyId()) ? null : Integer.valueOf(detail.getKeyId()));
        info.setContId(Integer.valueOf(request.getId()));
        info.setContName(detail.getLinkName());
        info.setPhone(detail.getLinkPhone());
        info.setSex(detail.getLinkSex() == null ? null : Integer.valueOf(detail.getLinkSex()));
        info.setLevle(detail.getLevel());
        info.setStorId(request.getStorCode());
        info.setEmail(detail.getLinkEmail());
        info.setMemCode(request.getMemCode() == null ? 0 : request.getMemCode());
        info.setVersion(StringUtils.isEmpty(detail.getKeyId()) ? null : 0);
        return info;
    }

    private TStorInfo modifyToStor(B092R request){
        TStorInfo info = new TStorInfo();
        info.setId(StringUtils.isEmpty(request.getId()) ? null : Integer.valueOf(request.getId()));
        info.setStorAbbr(request.getAbbrName());
        info.setAddress(request.getAddress());
        info.setStorArea(request.getStorArea());
        info.setStorPrup(request.getStorPurp());
        info.setStorCode(request.getStorCode());
        info.setStorName(request.getStorName());
        info.setStorType(StringUtils.isEmpty(request.getStorType()) ? null : Integer.valueOf(request.getStorType()));
//        info.setStopDate(StringUtils.isEmpty(request.getStopDate()) ? null : DateUtil.parseDate(request.getStopDate()));
        info.setStopDate(request.getStopDate());
        info.setStat(StringUtils.isEmpty(request.getStat()) ? null : Integer.valueOf(request.getStat()));
        return info;
    }
}
